using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkillObject_Sword : SkillObject_Base
{
    
    protected Skill_SwordThrow swordThrowManager;

    [Header("----- Sword Come Back Details -----")]
    [SerializeField] private float comebackSpeed = 30f;
    [SerializeField] private float maxRecoveryDistance = 20f;
    protected bool isClickRecycle;
    protected bool isCollide;
    protected Transform playerTrans;
    private float currentToPlayerDistance;
    protected override void Update()
    {
        base.Update();
        transform.right = rb.velocity;
        HandlerSwordComeBack();
    }
    public virtual void SetupSword(Skill_SwordThrow skill_SwordThrow, Vector2 initDirection)
    {
        rb.velocity = initDirection;
        swordThrowManager = skill_SwordThrow;
        playerTrans = swordThrowManager.transform.root;
        player = swordThrowManager.player;
        damageScaleData = swordThrowManager.damageScaleData;
    }
    //设置剑应该收回，当剑碰撞后点击右键才能收回
    public void SetSowrdShouldBack()
    {
        //当剑在碰撞到物体后才执行回收机制
        if (isCollide)
            isClickRecycle = true;
    }
    //设置剑收回，在旋转的剑掷出一段时间后自动调用，设置剑的收回状态为直接收回

    protected void HandlerSwordComeBack()
    {
        currentToPlayerDistance = Vector2.Distance(transform.position, playerTrans.position);
        if (currentToPlayerDistance > maxRecoveryDistance)
        {
            rb.simulated = false;
            isClickRecycle = true;
            isCollide = true;
        }
        if (isClickRecycle == false || isCollide == false)
            return;
        transform.position = Vector2.MoveTowards(transform.position, playerTrans.position, comebackSpeed * Time.deltaTime);

        if (currentToPlayerDistance < .5f)
        {
            swordThrowManager.SetSkillOnCoolDown();
            Destroy(gameObject);
        }
    }
    protected virtual void OnTriggerEnter2D(Collider2D collision)
    {
        StopSword(collision);
    }
    protected void StopSword(Collider2D collision)
    {
        rb.simulated = false;
        isCollide = true;
        transform.parent = collision.transform;
        DamageEnemiesInRedius(transform, 1f);
    }
    protected void SetBack()
    {
        isCollide = true;
        isClickRecycle = true;
    }
}
